package homework;

public class RuntimeDemo {
    public static void main(String[] args) {
        // 获取Runtime实例
        Runtime runtime = Runtime.getRuntime();

        // 1. 获取可用处理器数量
        int availableProcessors = runtime.availableProcessors();
        System.out.println("可用处理器数量: " + availableProcessors);

        // 2. 获取空闲内存量(MB)
        long freeMemory = runtime.freeMemory();
        double freeMemoryMB = bytesToMB(freeMemory);
        System.out.printf("JVM空闲内存量: %.2f MB\n", freeMemoryMB);

        // 3. 获取总内存量(MB)
        long totalMemory = runtime.totalMemory();
        double totalMemoryMB = bytesToMB(totalMemory);
        System.out.printf("JVM总内存量: %.2f MB\n", totalMemoryMB);

        // 4. 计算已使用内存量(MB)
        double usedMemoryMB = totalMemoryMB - freeMemoryMB;
        System.out.printf("JVM已使用内存量: %.2f MB\n", usedMemoryMB);

        // 5. 获取最大内存量(MB，如果未设置则为Long.MAX_VALUE)
        long maxMemory = runtime.maxMemory();
        double maxMemoryMB = bytesToMB(maxMemory);
        if (maxMemory != Long.MAX_VALUE) {
            System.out.printf("JVM最大可用内存量: %.2f MB\n", maxMemoryMB);
        } else {
            System.out.println("JVM最大可用内存量: 未设置限制");
        }
    }

    // 将字节转换为MB
    private static double bytesToMB(long bytes) {
        return bytes / (1024.0 * 1024.0);
    }
}
